<?php

namespace Modules\Admin\Http\Controllers\SiteMessage;

use Modules\Common\Models\AdminUser;
use Modules\Common\Models\Employee;
use Modules\Common\Models\EmployeeUser;
use Modules\Common\Models\Enterprise;
use Modules\Common\Models\EnterpriseUser;
use Modules\Common\Models\SiteMessage;
use Modules\Common\Util\Api;
use Illuminate\Support\Facades\Log;

class Retrieve
{
    /**
     *@Route(path=/api/admin/site-message)
    */
    public function retrieve()
    {
        $data = SiteMessage::where([])->orderBy('created_at', 'desc')->paginate(request('per_page', 15));
        if (count($data))
        {
            foreach ($data as &$item)
            {
                switch ($item->from_type)
                {
                    case 1:
                        $item->from_enterprise = EnterpriseUser::find($item->from_id, ['zh_name', 'mobile']);
                        break;
                    case 2:
                        $item->from_employee = EmployeeUser::leftjoin('employees', 'employees.employee_user_id', 'employee_users.id')
                            ->select(['employees.name', 'employee_users.mobile'])
                            ->where('employee_users.id', $item->from_id)
                            ->first();
                        break;
                }

                switch ($item->to_type)
                {
                    case 0:
                        $item->to_admin_user = AdminUser::find($item->to_id, ['zh_name', 'mobile']);
                        break;
                    case 1:
                        $enterprise_user = EnterpriseUser::find($item->to_id, ['id', 'mobile']);
                        $item->to_enterprise = Enterprise::where(['enterprise_user_id' => $enterprise_user->id])->first(['name']);
                        $item->to_enterprise->mobile = $enterprise_user->mobile;
                        break;
                    case 2:
                        $employee_user = EmployeeUser::find($item->to_id, ['id', 'mobile']);
                        $employee_user && $item->to_employee = Employee::where(['employee_user_id' => $employee_user->id])->first(['name']);
                        $employee_user && $item->to_employee->mobile = $employee_user->mobile;
                        break;
                }
            }
        }
        return Api::success($data);
    }
}
